import { Strategy } from 'passport-local';
import { PassportStrategy} from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { InjectModel } from 'nestjs-typegoose';
import { User } from '@libs/db/model/user.model';
import { ReturnModelType } from '@typegoose/typegoose';
import { hashSync,compareSync} from 'bcryptjs'



export class LocalStrategy extends PassportStrategy(Strategy,'local') {
  constructor(@InjectModel(User) public model: ReturnModelType<typeof User>) {
    super();
  }

  async validate(username: string, password: string): Promise<any> {
    const user = await this.model.findOne({username:username}).select('+password')
    if (!user) {
      throw new UnauthorizedException('用户不存在');
    }
    
    if(!compareSync(password,user.password)){
      throw new UnauthorizedException('密码不正确');
    }
  
    return user;
  }
}